package com.dcjt.firehotcarpad.service;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.Nullable;


import com.dcjt.firehotcarpad.R;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.List;
import java.util.Objects;

/**
 * Created by dongzhong on 2018/5/30.
 */

public class FloatingButtonServiceNew extends Service {
    public static boolean isStarted = false;

    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;

    //    private RadiusTextView button;
    private View button;
    private String id = null;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        Log.e("TAG", "FloatingButtonServiceNew" + "onCreate: ");
        isStarted = true;
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width = 155;
        layoutParams.height = 155;
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.x = this.windowManager.getDefaultDisplay().getWidth();
        layoutParams.y = (int) (this.windowManager.getDefaultDisplay().getHeight() * 0.75f);
    }

    @Override
    public void onDestroy() {
        layoutParams.width = 1;
        layoutParams.height = 1;
        if(button!= null){
            windowManager.updateViewLayout(button, layoutParams);
        }
        isStarted = false;
        EventBus.getDefault().unregister(this);

        super.onDestroy();
        Log.e("TAG", "FloatingButtonServiceNew" + "onDestroy: ");

    }

    @Subscriber(tag = "isForeground")
    public void onEventApplicationThread(boolean isForeground) throws Exception {
        Log.e("TAG", "onEventApplicationThread-button: 接收消息 "+isForeground);
        if (isForeground){
            //打开
            layoutParams.width = 155;
            layoutParams.height = 155;
            windowManager.updateViewLayout(button, layoutParams);
        } else {
            //关闭
            layoutParams.width = 1;
            layoutParams.height = 1;
            windowManager.updateViewLayout(button, layoutParams);

        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showFloatingWindow();
        return super.onStartCommand(intent, flags, startId);
    }

    @SuppressLint({"CheckResult", "ResourceAsColor"})
    private void showFloatingWindow() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(this)) {
            ImageView img = new ImageView(this);
            img.setImageResource(R.drawable.icon_voice_selector);
//            img.setScaleType(ImageView.ScaleType.CENTER);
            button = img;
            windowManager.addView(button, layoutParams);

            button.setOnTouchListener(new FloatingOnTouchListener());
            button.setOnClickListener(view -> {
                EventBus.getDefault().post(true,"isOpen");
            });
        }
    }

    /**
     * 判断本应用是否已经位于最前端
     *
     * @param context
     * @return 本应用已经位于最前端时，返回 true；否则返回 false
     */
    private boolean isRunningForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = Objects.requireNonNull(activityManager).getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfoList) {
            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName.equals(context.getApplicationInfo().processName)) {
                    return true;
                }
            }
        }
        return false;
    }

//    //当本应用位于后台时，则将它切换到最前端
//    public static void setTopApp(Context context) {
//        //获取ActivityManager
//        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
//
//        //获得当前运行的task(任务)
//        List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
//        for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
//            //找到本应用的 task，并将它切换到前台
//            if (taskInfo.topActivity.getPackageName().equals(context.getPackageName())) {
//                activityManager.moveTaskToFront(taskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
//                break;
//            }
//        }
//    }


    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;
        private Long mDownTime = 0L;

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    mDownTime = System.currentTimeMillis();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;
                    windowManager.updateViewLayout(view, layoutParams);
                    break;

                case MotionEvent.ACTION_UP:
                    return System.currentTimeMillis() - mDownTime > 200;
                default:
                    break;
            }
            return false;
        }
    }
}
